package com.leyou.test;

import com.leyou.demo.EsApplication;
import com.leyou.demo.pojo.Item;
import com.leyou.demo.repository.ItemRepository;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = EsApplication.class)
public class QuerySelfDemo {

    @Autowired
    private ItemRepository itemRepository;

    //自定义查询
    @Test
    public void queryWithTitle() {
        //构建查询条件对象
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        //添加分词查询
        queryBuilder.withQuery(QueryBuilders.matchQuery("title", "小米"));
        //搜索,获取结果
        Page<Item> search = this.itemRepository.search(queryBuilder.build());
        //得到了条数
        int totalPages = search.getTotalPages();
        List<Item> content = search.getContent();
        for (Item item : content) {
            System.out.println("item = " + item);
        }
    }

    //排序查询
    @Test
    public void querySortWithTitle() {
        //构建查询条件对象
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        //添加分词查询
        queryBuilder.withQuery(QueryBuilders.matchQuery("title", "小米"));
        //排序默认是升序的,这里将定义为降序排序的
        queryBuilder.withSort(SortBuilders.fieldSort("price").order(SortOrder.DESC));
        //搜索,获取结果
        Page<Item> search = this.itemRepository.search(queryBuilder.build());
        //得到了条数
        int totalPages = search.getTotalPages();
        List<Item> content = search.getContent();
        for (Item item : content) {
            System.out.println("item = " + item);
        }
    }

    //分页查询
    @Test
    public void queryPageWithTitle() {
        //构建查询条件对象
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        //添加分词查询
        queryBuilder.withQuery(QueryBuilders.matchQuery("category", "手机"));
        //在所有的springdata中所有的分页是从零开始的,分页不会改变排序的结果.
        queryBuilder.withPageable(PageRequest.of(0, 2));
        //排序默认是升序的,这里将定义为降序排序的
        queryBuilder.withSort(SortBuilders.fieldSort("price").order(SortOrder.DESC));
        //搜索,获取结果
        Page<Item> search = this.itemRepository.search(queryBuilder.build());

        int totalPages = search.getTotalPages();
        List<Item> content = search.getContent();
        for (Item item : content) {
            System.out.println("item = " + item);
        }
    }

}
